package com.pt.pok.string;

import com.pt.pok.*;
import com.pt.pok.model.PokerCommand;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Roman.Ivanov@playtech.com & Andrey.Panfilov@playtech.com
 * @date 1/23/12
 *       <p/>
 *       String message dispatcher
 */
class StringDispatcher
    implements Dispatcher<String> {

    private Map<Integer, CommandHandler<String>> idToCommandHandler = new ConcurrentHashMap<Integer, CommandHandler<String>>();

    private Map<Integer, ProtocolMarshaller<String>> idToProtocolMarshaller = new ConcurrentHashMap<Integer, ProtocolMarshaller<String>>();

    /**
     * @param pokerCommand
     * @return
     */
    public String convert(PokerCommand pokerCommand) {
        return idToProtocolMarshaller.get(pokerCommand.getClassId()).convertToProtocolCommand(pokerCommand);
    }

    /**
     * @param classId class id {@link com.pt.pok.model.ClassIds}
     * @param protocolMessage protocol formatted data
     * @return domain model object
     * @throws com.pt.pok.GeneralProxyException
     */
    public PokerCommand handleDirect(int classId, String protocolMessage)
        throws GeneralProxyException {
        return idToCommandHandler.get(classId).handleDirect(protocolMessage);
    }

    /**
     * @param classId
     * @param protocolMessage
     * @throws GeneralProxyException
     */

    public void handle(int classId, String protocolMessage)
        throws GeneralProxyException {
        idToCommandHandler.get(classId).handle(protocolMessage);
    }

    /**
     * @param classId
     * @param commandHandler
     */
    public void registerHandler(int classId, CommandHandler<String> commandHandler) {
        idToCommandHandler.put(classId, commandHandler);
    }

    /**
     * @param classId
     * @param marshaller
     */

    public void registerMarshaller(int classId, ProtocolMarshaller<String> marshaller) {
        idToProtocolMarshaller.put(classId, marshaller);
    }

    /**
     * @param classId
     */
    public void unRegisterHandler(int classId) {
        idToCommandHandler.remove(classId);
    }

    /**
     * @param classId
     */
    public void unRegisterMarshaller(int classId) {
        idToProtocolMarshaller.remove(classId);
    }

    public void addCommandListener(CommandListener commandListener) {
        for (CommandHandler<String> handler : idToCommandHandler.values()) {
            handler.addListener(commandListener);
        }
    }

    public void removeCommandListener(CommandListener commandListener) {
        for (CommandHandler<String> handler : idToCommandHandler.values()) {
            handler.removeListener(commandListener);
        }
    }
}
